package com.monco.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.monco.entity.User;
import com.monco.service.IUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * @ClassName MyMetaObjectHandler
 * @Description
 * @Author monco
 * @Date 2019/8/27 0:26
 * @Version 1.0
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private IUserService userService;

    @Override
    public void insertFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        List<User> userList = null;
        if (subject.getPrincipal() != null) {
            userList = userService.getUserList(new User().setUsername(subject.getPrincipal().toString()));
        }
        if (CollectionUtils.isNotEmpty(userList)) {
            this.setFieldValByName("createId", userList.get(0).getId(), metaObject);
            this.setFieldValByName("createDate", new Date(), metaObject);
            this.setFieldValByName("updateId", userList.get(0).getId(), metaObject);
            this.setFieldValByName("updateDate", new Date(), metaObject);
            this.setFieldValByName("createName", subject.getPrincipal(), metaObject);
            this.setFieldValByName("updateName", subject.getPrincipal(), metaObject);
        } else {
            this.setFieldValByName("createId", 1L, metaObject);
            this.setFieldValByName("createDate", new Date(), metaObject);
            this.setFieldValByName("updateId", 1L, metaObject);
            this.setFieldValByName("updateDate", new Date(), metaObject);
            this.setFieldValByName("createName", "system-init", metaObject);
            this.setFieldValByName("updateName", "system-init", metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Subject subject = SecurityUtils.getSubject();
        List<User> userList = userService.getUserList(new User().setUsername(subject.getPrincipal().toString()));
        if (CollectionUtils.isNotEmpty(userList)) {
            this.setFieldValByName("updateId", userList.get(0).getId(), metaObject);
            this.setFieldValByName("updateName", subject.getPrincipal(), metaObject);
            this.setFieldValByName("updateDate", new Date(), metaObject);
        }

    }
}
